package me.jollyfly.jshop.framework.aop

import me.jollyfly.jshop.common.bean.ResultBean
import me.jollyfly.jshop.common.exception.JshopException
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.slf4j.LoggerFactory
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component

/**
 * @author jollyfly
 */

@Aspect
@Component
@Order
class ControllerAspect {

    @Around(value = "@annotation(logRecord))")
    fun onService(pjp: ProceedingJoinPoint, logRecord: LogRecord): Any {
        val startTime = System.currentTimeMillis()
        var resultBean: ResultBean<*>
        try {
            resultBean = pjp.proceed() as ResultBean<*>
            val endTime = System.currentTimeMillis()
            logger.info("{},{},use time: {} ms", pjp.signature, logRecord.value, endTime - startTime)

            if (logRecord.writeToMongo) {
                //TODO 推送日志信息到MongoDB
            }
        } catch (e: Throwable) {
            resultBean = handlerException(pjp, e)
        }

        return resultBean
    }

    private fun handlerException(pjp: ProceedingJoinPoint, e: Throwable): ResultBean<*> {
        val result = ResultBean<Any>()
        // 已知异常
        if (e is JshopException) {
            throw JshopException(e)
        } else {
            logger.error(pjp.signature.toString() + " error ", e)
            result.msg = e.toString()
            result.code = ResultBean.FAIL
            // 未知异常是应该重点关注的，这里可以做其他操作，如通知邮件，单独写到某个文件等等。
        }
        return result
    }

    companion object {

        private val logger = LoggerFactory.getLogger(ControllerAspect::class.java)
    }


}
